<?php

require_once LIBS_DIRECTORY.OS_PATH_SEPARATOR.'jglib'.OS_PATH_SEPARATOR.'baseFile.php';

/*
 * Specific phplister3 file class with save to hard drive support
 * and save to database support
 */
class File extends BaseFile
{
	// Internal database unique id
	private $databaseId;

	// Get the internal database unique id
	public function getId()
	{
		return $this->databaseId;
	}

	// Save the file in the database
	private function DBSave()
	{
		global $DB;
		$this->databaseId = $DB->getNextId('item');
		
		$uri = UPLOAD_DIRECTORY.OS_PATH_SEPARATOR.$this->databaseId.'-'.$this->getSafeFileName();
		
		$query = debug('
			INSERT INTO '.ITEM_TABLE.' (id, name, creation_time, hash, type, user, right, uri)
			VALUES(
				'.(int)$this->databaseId.',
				"'.$DB->escapeString($this->getReadableFileName()).'",
				'.time().',
				"'.''.'",
				'.(int)$this->getType().',
				1,
				1,
				"'.$DB->escapeString($uri).'")
		','SQL', JGLIB_DEBUG_SQLQ);
		$DB->queryExec($query);
		$DB->counterIncrement(COUNTER_TYPE_NAME.$this->getType());
	}
	
	// Delete the file from the database, removing metadata as well
	private function DBDelete()
	{
		//TODO
	}

	/**
	 * Trouve le type de l'item selon le mime du fichier ou extention sinon
	 *
	 * @return int $type type trouvé
	 */
	// Get the file type see config.php
	public function getType()
	{

		$mime = $this->getMimeType();
		$ext  = $this->getExtension();

		if(ereg('^audio', $mime)) return AUD;
		if(ereg('^video', $mime)) return VID;
		if(ereg('^image', $mime)) return IMG;
		//if(ereg('^text' , $mime)) return DOC;

		// mime speciaux
		if(
			$mime == 'application/pdf'              ||
			$mime == 'application/msword'           ||
			$mime == 'application/postscript'       ||
			$mime == 'application/rtf'              ||
			ereg('^application/wordperfect', $mime) ||
			ereg('excel$', $mime)                   ||
			ereg('powerpoint$', $mime)              ||
			ereg('\.opendocument\.', $mime)         ||
			ereg('\.sun\.xml\.', $mime)
		)
		{
			return DOC;
		}
	
		if($mime == 'application/ogg') return AUD;
		if($mime == 'application/rar' || $mime == 'application/zip') return OTH;

		global $TYPE;
		global $TYPE_LIST;
		foreach($TYPE_LIST as $t)
		{
			if(isset($TYPE[$t]) && in_array($ext, $TYPE[$t])) return $t;
		}

		// defaut
		return OTH;
	}
	
	// Save the file on the hard drive then on the database see Database::DBSave()
	public function save()
	{
		$this->DBSave();
		
		$path = UPLOAD_DIRECTORY.OS_PATH_SEPARATOR.$this->databaseId.'-'.$this->getSafeFileName();
		rename($this->uri, $path);
		$this->uri = $path;

		return $path;
	}
	
	// Delete the file from the hard drive then from the database see Database::DBDelete()
	public function delete()
	{
		//TODO
		$this->DBDelete();
		return false;
	}
	
	public function getSafeFileName()
	{
		return strtolower(substr(md5(HASH_SEED.time()),0,6).'-'.ereg_replace('[^a-zA-Z0-9\.]', '_', debug(basename($this->name),'Name used for the safe name', JGLIB_DEBUG_PER3)));
	}
}
